# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner,aq_parent
from plone.memoize.compress import xhtml_compress
from Products.bpContents.aviso import IAviso
from Products.ATContentTypes.interfaces import IATDocument
from zope.site.hooks import getSite
import unicodedata
from Products.bpContents.utils import Utilidades


class ICategoriasPortlet(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=3)



class Assignment(base.Assignment):
    implements(ICategoriasPortlet)

    def __init__(self, count=5,canal=[], categoria=[]):
        self.count = count

    @property
    def title(self):
        return _(u"Ctegorias")

class Renderer(base.Renderer):
    render = ViewPageTemplateFile('categorias_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.atvm = getToolByName(context , 'portal_vocabularies')
        self.engines = self.atvm.getVocabularyByName('categorias_vocab')
        self.catalog = plone_tools.catalog()
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()
        self.utils= Utilidades()
        self.seccionActual= self.utils.dameRutaSeccion(self.context)

    @property
    def available(self):
        return True
        #len(self._data())>0

    def getRamas(self):
        return self._data()

    def dameSeccion(self):
        """devuelve la seccion en la que me encuentro"""
        return self.seccionActual


    @memoize
    def _data(self):

        uid_catalog=self.context.uid_catalog
        ramas=[]
        subCatUsadas=[]
        listTopes=[]
        flagRama=0

        if not self.seccionActual:
            return ramas

        enUso=[]
        objCat=self.catalog(
            portal_type=("Products.bpContents.articulo",
                         "Products.bpContents.evento",
                         "Products.bpContents.libro"),
            path={"query":self.seccionActual,"depth":2})



        ttopes=self.catalog(path={"query":"publica/portal_vocabularies/categorias_vocab","depth":1})


        for ramaIndice in ttopes:
            rama=self.context.unrestrictedTraverse(ramaIndice.getPath())
            uuiRama= rama.UID()
            objRama=dict()
            objRama['titulo']=rama.Title()
            objRama['content']=[]
            objRama['UID']=uuiRama
            objRama['cantItems']=0
            objRama['visible']=False
            objRama['imgNumer']=rama.title.lower().replace(" ","_")

            ramas.append(objRama)


        for obj in objCat:
            tmpO    =   self.context.unrestrictedTraverse(obj.getPath())

            for subCat in tmpO.categorias:
                uid=subCat.split(":")[0]
                nombres=subCat.split(":")[1]

                catName=""
                subCatName=""

                catName=nombres
                #if self.find_in_list(subCatName,subCatUsadas)==-1:
                if len(self.catalog(UID=uid))>0:
                    acomoda=self.acomodaEnLaRama(ramas,{"uid":uid,"titulo":catName,"categoria":nombres,"id":"id_"})
                    subCatUsadas.append(subCatName)

        return ramas

    def find_in_list(self,element,list_element):
        try:
            index_element=list_element.index(element)
            return index_element
        except ValueError:
            return -1

    def acomodaEnLaRama(self,dic,datos):
        """Dado un diccionario, busca la rama a la que pretence y guarda el dato"""
        flag=False
        termino=self.catalog(UID=datos["uid"])[0]
        termObj=self.context.unrestrictedTraverse(termino.getPath())
        termTope=aq_parent(termObj)

        if termTope.id=="categorias_vocab":
            for elemA in dic:
                if elemA["titulo"]==termino.Title:
                    elemA['visible']=True
            return True

        for elem in dic:
            if elem["titulo"]==termTope.title:
                elem["content"].append(self.empaquetaDatos(datos))
                elem["cantItems"]+=1
                elem['visible']=True
                flag=True

        return flag


    def empaquetaDatos(self,datos):
        """devuelve un diccionario con los datos para el renderizado"""
        itemR=dict()
        itemR["titulo"]=datos["categoria"]
        itemR["uid"]=datos["uid"]
        itemR["id"]=datos["id"]
        itemR["url"]=self.seccionActual+"/@@categoriaList_view?rama="+datos["uid"]
        return itemR

class AddForm(base.AddForm):
    form_fields = form.Fields(ICategoriasPortlet)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3))

class EditForm(base.EditForm):
    form_fields = form.Fields(ICategoriasPortlet)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

